package org.devocean.groupbuying.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.devocean.groupbuying.dao.ArticlesLocalizationDAO;
import org.devocean.groupbuying.domain.Article;
import org.devocean.groupbuying.domain.ArticlesLocalization;
import org.springframework.stereotype.Repository;

@Repository
public class ArticlesLocalizationDAOImpl implements ArticlesLocalizationDAO {

	@PersistenceContext
	private EntityManager em;

	public void linkToArticle(ArticlesLocalization articlesLocalization) {
		
		for (Article article : articlesLocalization.getArticles()) {
			article.setArticlesLocalization(articlesLocalization);
		}

	}


	public ArticlesLocalization saveArticlesLocalization(
			ArticlesLocalization articlesLocalization) {
		linkToArticle(articlesLocalization);
		em.persist(articlesLocalization);
		em.flush();
		return articlesLocalization;
	}

	public void deleteArticlesLocalization(Integer id) {
		final ArticlesLocalization localisationKey = em.find(
				ArticlesLocalization.class, id);
		em.remove(localisationKey);
	}

	
	public ArticlesLocalization findArticleById(Integer articleId) {

		final Query query = em
				.createQuery("select distinct al from ArticlesLocalization al  INNER JOIN FETCH al.articles a where  a.id=:articleID");
		query.setParameter("articleId", articleId);

		return (ArticlesLocalization) query.getResultList().get(0);

	}

	public ArticlesLocalization updateArticlesLocalization(
			ArticlesLocalization articlesLocalization) {
		
		linkToArticle(articlesLocalization);
		
		final ArticlesLocalization merged = em.merge(articlesLocalization);
		em.flush();
		return merged;
	}

	public ArticlesLocalization findArticleBylang(Integer LocalizationKey,
			String language) {
		final Query query = em
				.createQuery("select distinct al from ArticlesLocalization al  LEFT JOIN FETCH al.articles a where  al.articlesLocalizationID=:LocalizationKey and a.lang=:language");
		query.setParameter("LocalizationKey", LocalizationKey).setParameter(
				"language", language);

		if (query.getResultList().size() > 0) {
			return (ArticlesLocalization) query.getResultList().get(0);
		} else {
			final ArticlesLocalization articlesLocalization = findArticleLocalizationById(LocalizationKey);
			articlesLocalization.setArticles(null);
			return articlesLocalization;
		}

	}

	public ArticlesLocalization findArticleLocalizationById(Integer id) {
		return em.find(ArticlesLocalization.class, id);
	}

}
